//
//  NGMessageListViewController.m
//  NetMobileLocation
//
//  Created by Mehmet Sinan Şahin on 2/9/12.
//  Copyright (c) 2012 netgis. All rights reserved.
//

#import "NGMessageListViewController.h"
#import "SetLocationsResponse.h"
#import "NSDate+Extensions.h"
#import "NGDBHelper.h"
#import "NGMessageViewController.h"
#import "NGLocalMessageViewController.h"
#import "MessageRow.h"
#import "NGAppDelegate.h"
#import "LoadingView.h"
#import <QuartzCore/QuartzCore.h>


@implementation NGMessageListViewController

@synthesize messageTable;
@synthesize toLocationsButton;
@synthesize navItem;
@synthesize segCtrlMessageFilter;
@synthesize viewNewMessage;
@synthesize btnNewTextMessage;
@synthesize btnNewAlarmMessage;


- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.title = TTLocalizedString(@"Messages", @"");
        self.tabBarItem.image = [UIImage imageNamed:@"message"];
        UIButton* backButton = [UIButton buttonWithType:101];
        [backButton setTitle:TTLocalizedString(@"Locations", @"") forState:UIControlStateNormal];        
        [backButton addTarget:self
                       action:@selector(toLocations:)
             forControlEvents:UIControlEventTouchUpInside];
        toLocationsButton = [[UIBarButtonItem alloc] initWithCustomView: backButton];        

    }
    return self;
}

-(IBAction)toLocations:(id)sender {
    [self.tabBarController setSelectedIndex:0];
    NGAppDelegate *appDelegate = (NGAppDelegate *) [[UIApplication sharedApplication] delegate];
    [appDelegate makeTabBarHidden:FALSE];     
}

#pragma mark - button actions

/*
 * Insert Test message into database
 */
-(IBAction) insertTestMessage: (id) sender {
    Message *message = [[Message alloc] init];
    message.Sender = @"Sender-sinan";
    message.Time = [[NSDate date] toFormattedString];
    message.command = @"command";
    message.commandParameter = @"c-p";
        
    NGDBHelper *db = [NGDBHelper openDatabase];
    [db insertMessage: message];
    [self.messageTable reloadData];
    [self viewWillAppear:FALSE];
}

-(IBAction) deleteAllMessage: (id)sender {
    [messageTable setEditing:![messageTable isEditing] animated:YES];
}

-(IBAction) newLocalMessage: (id)sender {
    [viewNewMessage setHidden:!viewNewMessage.hidden];
}

-(IBAction) refresh:(id)sender {
    [self filterMessages:sender];
}

-(IBAction) closeNewMessageView:(id)sender {
    [viewNewMessage setHidden:TRUE];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

#pragma mark - table delegations

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // Number of rows
    return [messages count];
}


- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    return @"";
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *cellIdentifier = @"Message";
    
    MessageRow *cell = (MessageRow *)[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (cell == nil) {
        NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:@"MessageRow" owner:self options:nil];
        for (id currentObj in topLevelObjects) {
            if ([currentObj isKindOfClass:[UITableViewCell class]]) {
                cell = (MessageRow *) currentObj;
            }
        }
    }
    
    Message *message = [messages objectAtIndex:indexPath.row];
    [cell.lblMessageHeader setText:[message viewMessageHeader]];
    [cell.lblMessageBody setText:[message viewMessageBody]];
    //[cell.lblDate setText:message.Time]; //friendly
    
    NSDate *date = [message.Time toDateWithDot];
    [cell.lblDate setText:[date formatRelativeTime]];
    
    if ([message isMessage]) {
        [cell.imgMessageType setImage:[UIImage imageNamed: @"message_type_text.png"]];
    }
    else if ([message isCommand]) {
        [cell.imgMessageType setImage:[UIImage imageNamed: @"message_type_command.png"]];        
    }    
    
    if (!message.read) {
        [cell makeAsUnread];
    } else {
        [cell makeAsRead];
    }
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    Message *message = [messages objectAtIndex:indexPath.row];
    if ([message isMessage])
        return 70;
    if ([message isCommand])
        return 60;
    return 40;
}

- (void)tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath {    
    Message *message = [messages objectAtIndex:indexPath.row];
    if (!message.read) {
        [((MessageRow *)[tableView cellForRowAtIndexPath:indexPath]) makeAsRead];
    }
    NGMessageViewController *messageViewCtrl = [[[NGMessageViewController alloc] initWithNibName:@"NGMessageViewController" bundle:nil] autorelease];
    messageViewCtrl.message = [message retain];
    [self.view addSubview: messageViewCtrl.view];
    [messageViewCtrl viewWillAppear: FALSE];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
	[tableView deselectRowAtIndexPath:indexPath animated:YES];
}



//Override to support conditional editing of the table view.
 - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
     //Return NO if you do not want the specified item to be editable.
     return YES;
}



- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
	
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        Message *message = [messages objectAtIndex:indexPath.row];
        NGDBHelper *db = [NGDBHelper openDatabase];
        if ([db deleteMessageWithId:message._id]) {
            [messages removeObjectAtIndex:indexPath.row];
            [self.messageTable reloadData];
            [self viewWillAppear:FALSE];
        }
    }
}

- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath {
    return TTLocalizedString(@"Delete", @"Sil");
}

#pragma mark - message filter segmented control delegate
- (IBAction)filterMessages:(id)sender {
    
    LoadingView *loadingView =
    [LoadingView loadingViewInView:[self.view.window.subviews objectAtIndex:0]];
	
	[loadingView
     performSelector:@selector(removeView)
     withObject:nil
     afterDelay:5.0];
    
    [self closeNewMessageView:sender];
    
    [messages release];
    if (segCtrlMessageFilter.selectedSegmentIndex == 0) { //Text Messages
        messages = [[NGDBHelper openDatabase] listMessages:MESSAGE]; 
    } else if (segCtrlMessageFilter.selectedSegmentIndex == 1) { //All
        messages = [[NGDBHelper openDatabase] listAllMessages]; 
        [self.messageTable reloadData];
    } else if (segCtrlMessageFilter.selectedSegmentIndex == 2) {
        messages = [[NGDBHelper openDatabase] listMessages:COMMAND]; 
    }
    [self.messageTable reloadData];
    [loadingView removeView];
}

#pragma mark - new message buttons delegate
/*show local message view*/
- (IBAction) createMessage:(id)sender {
    LOCAL_MESSAGE_TYPE _messageType;
    if (sender == btnNewAlarmMessage)
        _messageType = LOCAL_MESSAGE_TYPE_ALARM;
    else if (sender == btnNewTextMessage)
        _messageType = LOCAL_MESSAGE_TYPE_TEXT;
    else {
        NSLog(@"Tanımsız tip");
        return;
    }
    
    NGLocalMessageViewController *newLocalMessageView = [[[NGLocalMessageViewController alloc] initWithNibName:@"NGLocalMessageViewController" bundle:nil messageType:_messageType] autorelease];
        
    [self.view addSubview:newLocalMessageView.view];
}    

#pragma mark - View lifecycle

- (void)viewWillAppear:(BOOL)animated {
    [segCtrlMessageFilter setSelectedSegmentIndex:1]; //All
    messages = [[NGDBHelper openDatabase] listAllMessages]; 
    [self.messageTable reloadData];
    [self closeNewMessageView:nil];
    [messageTable setEditing:NO animated:YES];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    [viewNewMessage.layer setCornerRadius:5.0f];

    [viewNewMessage setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"bg.png"]]];
    [viewNewMessage.layer setCornerRadius:5.0f];
    [viewNewMessage.layer setMasksToBounds:YES];

    // Do any additional setup after loading the view from its nib.
    messageTable.delegate = self;
    messageTable.dataSource = self;
    [navItem setLeftBarButtonItem:toLocationsButton animated:FALSE];
    [segCtrlMessageFilter addTarget:self
                         action:@selector(filterMessages:)
               forControlEvents:UIControlEventValueChanged];
    [viewNewMessage setHidden:TRUE];
 
    [btnNewTextMessage addTarget:self action:@selector(createMessage:) forControlEvents:UIControlEventTouchUpInside];
    [btnNewAlarmMessage addTarget:self action:@selector(createMessage:) forControlEvents:UIControlEventTouchUpInside];

    
    [lblBtnAlarmMessage setText:TTLocalizedString(@"Alarm", @"")];
    [lblBtnAlarmMessage setUserInteractionEnabled:TRUE];
    [lblBtnTextMessage setText:TTLocalizedString(@"Text", @"")];
    [lblBtnTextMessage setUserInteractionEnabled:TRUE];
    
    UITapGestureRecognizer *recognizerText = [[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapActionForText)] autorelease];
    UITapGestureRecognizer *recognizerAlarm = [[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapActionForAlarm)] autorelease];
    
    [lblBtnTextMessage addGestureRecognizer:recognizerText];
    [lblBtnAlarmMessage addGestureRecognizer:recognizerAlarm];
    
    [segCtrlMessageFilter setTitle:TTLocalizedString(@"Text", @"") forSegmentAtIndex:0];
    [segCtrlMessageFilter setTitle:TTLocalizedString(@"See All", @"") forSegmentAtIndex:1];
    [segCtrlMessageFilter setTitle:TTLocalizedString(@"Command", @"") forSegmentAtIndex:2];
}

- (void)tapActionForText {
    [self createMessage:btnNewTextMessage];
}


- (void)tapActionForAlarm {
    [self createMessage:btnNewAlarmMessage];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

- (void)dealloc {
    [messages release];
    [super dealloc];
}

@end
